package org.ala.tiktools.sharddb.db.provider;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.sql.DataSource;

import org.ala.tiktools.logs.LoggerFactory;
import org.ala.tiktools.sharddb.Namespace;
import org.ala.tiktools.sharddb.db.config.ShardDataSourceConfigInfo;
import org.ala.tiktools.sharddb.db.config.ShardDataSourceConfigInfoParser;
import org.ala.tiktools.sharddb.db.provider.druid.DruidDatasourceProvider;
import org.ala.tiktools.sharddb.db.provider.hikari.HikariCPDatasourceProvider;
import org.slf4j.Logger;
import org.springframework.jdbc.datasource.lookup.DataSourceLookup;
import org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException;
import org.springframework.util.Assert;

/**
 * 数据源提供者
 *
 * @author ala
 * @date 2024-12-27 12:23
 */
public class ShardDatasourceProvider implements DataSourceLookup {


    static Logger log = LoggerFactory.getLogger("tiktools", "sharddb");


    /**
     *  配置信息
     */
    protected ShardDataSourceConfigInfoParser configParser;
    /**
     *  mapper
     */
    protected Map<String, DataSource> datasourceMapper = new ConcurrentHashMap<>();
    /**
     *  数据源提供器
     */
    protected Map<String, IDatasourceProvider> providerMap;

    /**
     *  初始化提供器类型
     */
    public void initProider() {
        providerMap = new HashMap<>();
        providerMap.put(Namespace.SHARD_DATASOURCE_TYPE_DRUID, new DruidDatasourceProvider());
        providerMap.put(Namespace.SHARD_DATASOURCE_TYPE_HIKARI, new HikariCPDatasourceProvider());
    }

    /**
     *  初始化数据源
     */
    public DataSource getDatasource(String key) {
        DataSource dataSource = datasourceMapper.get(key);
        if (dataSource == null) {
            synchronized (key.intern()) {
                dataSource = datasourceMapper.get(key);
                if (dataSource == null) {
                    ShardDataSourceConfigInfo configInfo = configParser.getConfigInfo(key);
                    Assert.notNull(configInfo, String.format("[ShardDatasourceProvider getDatasource] 找不到数据源配置信息:%s", key));

                    IDatasourceProvider provider = providerMap.get(configInfo.getType());
                    Assert.notNull(provider, String.format("[ShardDatasourceProvider getDatasource] 找不到数据源类型:%s", configInfo.getType()));

                    dataSource = provider.getDataSource(configInfo);
                    datasourceMapper.put(key, dataSource);
                }
            }
        }
        return dataSource;
    }

    @Override
    public DataSource getDataSource(String key) throws DataSourceLookupFailureException {
        return getDatasource(key);
    }

    public ShardDataSourceConfigInfoParser getConfigParser() {
        return configParser;
    }

    public void setConfigParser(ShardDataSourceConfigInfoParser configParser) {
        this.configParser = configParser;
    }
}
